package com.fzd.code.http;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.stereotype.Component;

import javax.mail.internet.MimeUtility;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class HttpUtil {
	
	public String post(String url,Map<IParam,String> param,String requestCharset,String responseCharset) throws Exception{
		log.info("请求："+url);
		log.info("参数："+JSONObject.toJSONString(param));


		CloseableHttpClient httpClient=null;
		BufferedReader reader=null;
		CloseableHttpResponse response=null;

        try {
        	//请求地址
    		httpClient=HttpClients.createDefault();
    		HttpPost httpPost=new HttpPost(url);
    		//请求参数
    		List<NameValuePair> formParams = new ArrayList<NameValuePair>();
			if(param!=null){
				for(IParam paramName:param.keySet()){
					formParams.add(new BasicNameValuePair(paramName.paramToString(), param.get(paramName)));
				}
			}

            httpPost.setEntity(new UrlEncodedFormEntity(formParams, requestCharset));
            //发送请求
            response = httpClient.execute(httpPost);

            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {

            	StringBuffer lines=new StringBuffer();
            	reader=new BufferedReader(new InputStreamReader(responseEntity.getContent(), responseCharset));
            	String line=null;
            	while((line=reader.readLine())!=null){
            		lines.append(line);
            	}


				log.info("响应："+lines.toString());

            	return lines.toString();
            }
        }finally {
        	close(reader,response,httpClient);
        }

		return null;
	}

	public String get(String url,String responseCharset) throws Exception{
		log.info("请求："+url);

		CloseableHttpClient httpClient=null;
		BufferedReader reader=null;
		CloseableHttpResponse response=null;

		try {
			//请求地址
			httpClient=HttpClients.createDefault();
			HttpGet httpGet=new HttpGet(url);
			//发送请求
			response = httpClient.execute(httpGet);

			HttpEntity responseEntity = response.getEntity();
			if (responseEntity != null) {

				StringBuffer lines=new StringBuffer();
				reader=new BufferedReader(new InputStreamReader(responseEntity.getContent(), responseCharset));
				String line=null;
				while((line=reader.readLine())!=null){
					lines.append(line);
				}


				log.info("响应："+lines.toString());

				return lines.toString();
			}
		}finally {
			close(reader,response,httpClient);
		}

		return null;
	}

	private void close(BufferedReader reader,CloseableHttpResponse response,CloseableHttpClient httpClient) throws Exception{
		try {
			if (reader!=null) {
				reader.close();
			}
		} catch (Exception e) {
			throw e;
		}

		try {
			if (response!=null) {
				response.close();
			}
		} catch (Exception e) {
			throw e;
		}

		try {
			if (httpClient!=null) {
				httpClient.close();
			}
		} catch (IOException e) {
			throw e;
		}
	}
	
	
	public static String getReponseHeader_ContentDisposition(String fileName, String userAgent)
			throws Exception {
		// 如果没有UA，则默认使用IE的方式进行编码，因为毕竟IE还是占多数的
		String newFileName = URLEncoder.encode(fileName, "UTF-8");
		String convertFileName = "filename=\"" + newFileName + "\"";
		
		if (userAgent != null) {
			userAgent = userAgent.toLowerCase();
			
			// IE浏览器，只能采用URLEncoder编码
			if (userAgent.indexOf("msie") >-1) {
				convertFileName = "filename=\"" + newFileName + "\"";
			}
			
			// Opera浏览器只能采用filename*
			else if (userAgent.indexOf("opera") >-1) {
				convertFileName = "filename*=UTF-8''" + newFileName;
			}
			
			// Safari浏览器，只能采用ISO编码的中文输出
			else if (userAgent.indexOf("safari") >-1) {
				convertFileName = "filename=\""
						+ new String(fileName.getBytes("UTF-8"), "ISO8859-1")
						+ "\"";
			}
			
			// Chrome浏览器，只能采用MimeUtility编码或ISO编码的中文输出
			else if (userAgent.indexOf("applewebkit") >-1) {
				newFileName = MimeUtility.encodeText(fileName, "UTF-8", "B");
				convertFileName = "filename=\"" + newFileName + "\"";
			}
			
			// FireFox浏览器，可以使用MimeUtility或filename*或ISO编码的中文输出
			else if (userAgent.indexOf("mozilla") >-1) {
				convertFileName = "filename*=UTF-8''" + newFileName;
			}
		}
		convertFileName = convertFileName.replaceAll("\\+", "%20");
		return convertFileName;
	}
	public static String getUserAgent(HttpServletRequest request){
		return request.getHeader("user-agent");
	}

//	public static void main(String[] args) throws Exception{
//		String response = new HttpUtil().get("http://www.qq.com","utf-8");
//		System.out.println(response);
//	}
}
